package middleware

import (
	"context"
	"gitee.com/jinmingzhi/cdce-service/pkg/auth"
	"gitee.com/jinmingzhi/cdce-service/pkg/errs"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"strings"
)

func Auth() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		token, err := ExtractToken(ctx)
		if err != nil {
			return nil, status.Errorf(codes.Unauthenticated, errs.ErrInvalidToken.Error())
		}
		uid, err := auth.GetUid(token)
		if err != nil {
			return nil, status.Errorf(codes.Unauthenticated, errs.ErrInvalidToken.Error())
		}
		outCtx := context.WithValue(ctx, "uid", uid)
		return handler(outCtx, req)
	}
}

func ExtractToken(ctx context.Context) (string, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return "", errs.ErrMissingMetadata
	}

	array := md["authorization"]
	if len(array) < 1 {
		return "", errs.ErrEmptyAuthorization
	}

	return strings.TrimPrefix(array[0], "Bearer "), nil
}
